#include "scoreitem.h"
#include "recource.h"
#include <QPainter>

ScoreItem::ScoreItem(QPixmap* pixmap):
    m_x(0.0),
    m_pixmap(pixmap)
{
   setCacheMode(QGraphicsItem::DeviceCoordinateCache);
   m_timer.setInterval(50);
   connect(&m_timer,SIGNAL(timeout()),this,SLOT(increaseNum()));
}

ScoreItem::~ScoreItem()
{

}

void ScoreItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    if(m_numarr.isEmpty())
    {
        painter->drawPixmap(QRectF(0.0,0.0,16.0,20.0),*m_pixmap,
                            QRectF(0.0,0.0,16.0,20.0));
    }
    else
    {
        for(int i = 0; i < m_numarr.count();++i)
        {
            painter->drawPixmap(QRectF((m_numarr.count() - i -1) * 16.0,0.0,16.0,20.0),
                                *m_pixmap,
                                QRectF(m_numarr.at(i) * 16.0,0.0,16.0,20.0));
        }
    }
}

QRectF ScoreItem::boundingRect() const
{
    return QRectF(0.0,0.0,128,20);
}

void ScoreItem::setNum(int iNum,bool banima)
{
    m_iincreasNum = iNum - m_num;
    if(m_iincreasNum > 1 && banima)
    {
       m_timer.start();
    }
    else
    {
        m_num = iNum;
        showNum(m_num);
    }
}

void ScoreItem::increaseNum()
{
    if(m_iincreasNum < 1)
    {
        m_timer.stop();
        return;
    }
    else if(m_iincreasNum < 10)
    {
        m_num += 1;
        m_iincreasNum -= 1;
    }
    else if(m_iincreasNum < 100)
    {
        m_num += 10;
        m_iincreasNum -= 10;
    }
    else if(m_iincreasNum < 1000)
    {
        m_num += 100;
        m_iincreasNum -= 100;
    }
    else if(m_iincreasNum < 10000)
    {
        m_num += 1000;
        m_iincreasNum -= 1000;
    }
    else if(m_iincreasNum < 100000)
    {
        m_num += 10000;
        m_iincreasNum -= 10000;
    }
    else if(m_iincreasNum < 1000000)
    {
        m_num += 100000;
        m_iincreasNum -= 100000;
    }
    else
    {
        m_num += 1000000;
        m_iincreasNum -= 1000000;
    }

    showNum(m_num);
}

void ScoreItem::showNum(int iNum)
{
    m_numarr.clear();
    if(iNum <= 0)
    {
        m_numarr.append(0);
    }
    else
    {
        while(iNum)
        {
            m_numarr.append(iNum % 10);
            iNum = iNum / 10;
        }
    }
    setX(m_x - m_numarr.count() * 16.0);
    update();
}


